package com.tx.blog.user.controller;

import com.tx.blog.user.service.IUserService;
import com.tx.blog.user.vo.UserVo;
import com.tx.blog.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/toLogin")
public class UserLoginController {

    @Autowired
    IUserService userService;

    @RequestMapping("/checkUser")
    public ModelAndView checkUser(UserVo user, HttpServletRequest request, RedirectAttributes attributes){
        UserVo dbUser = userService.findUserByUserName(user);
        ModelAndView mv = new ModelAndView("redirect:/login");
        if(dbUser == null || user == null){
            attributes.addFlashAttribute("msg","用户不存在!");
           return mv;
        }
        String salt = dbUser.getSalt();
        String md5Pwd = Md5Util.convertToDBPass(user.getPassword(),salt);
        if(!md5Pwd.equals(dbUser.getPassword())){
            attributes.addFlashAttribute("msg","用户名或密码错误!");
            return mv;
        }
        request.getSession().setAttribute("user",dbUser);
        ModelAndView mv2 = new ModelAndView("redirect:/index");
        attributes.addFlashAttribute("user",dbUser);
        return mv2;
    }
}
